import React from 'react';
import { Cascader, Select, Spin, Button } from 'antd';

import TBasePage from '#/base/TBasePage';
import { TRAlert, TRDefault } from '#/components';
import { CaretDownOutlined } from '#/utils/antdIcons';
import emitter from '#/utils/events';
import renovate from '#/utils/renovate';
import { HttpCode } from '#/utils/contacts.js';
import { powersDataType } from '#/utils/userHelper';
import { onCheckFeed } from '#/utils/interactive';
import { isDark as TDark } from '#/utils/utils';
import { queryDataPower, postQueryProvinceList, queryDataPowerToTianJi } from '@/services/user';
import styles from './index.less';
import { buildPower, getTreeByCodes } from '@/utils';

function filter(inputValue, path) {
  return path.some((option) => option.label.indexOf(inputValue) > -1);
}

function filterList(array) {
  let list = [];
  array.forEach((item) => {
    let obj = { value: item.value, label: item.lable };
    if (item.children) {
      obj.children = filterList(item.children || []);
    }
    list.push(obj);
  });
  return list;
}

export default class TMainBasePage extends TBasePage {
  constructor(props) {
    super(props);
    this.state = {
      spinLoding: false,
      stationList: [], //结算单元
      selectStationList: [], //所选中的结算单元
      selectStationId: 0, //所选中的结算单元id
      newStationList: [], //结算单元
      newSelectStationList: [], //所选中的结算单元
      newSelectStationId: 0, //所选中的结算单元id
      selectRegionList: [], //所选中的区域
      dataSourceList: [], //数据线信息
      provinceId: '', // 省份id
      selectDeptList: [],
      deptList: [],
      selectDeptId: 0,
      decomposeStrategyList: [], //策略集数组
      regionList: [], //区域
      errorMsg: '',
    };
    this._isSpinLoading_ = false;
  }

  componentDidMount() {
    renovate.isRenovate = false;
  }

  async _onGetStation(callBack, menuCode) {
    this.setState({ spinLoding: true });
    const [res, res1] = await Promise.all([
      queryDataPower(menuCode),
      postQueryProvinceList(menuCode),
    ]);
    this._isSpinLoading_ = false;
    if (res?.statusCode === HttpCode.SUCCESS && res1?.statusCode === HttpCode.SUCCESS) {
      let powerObj = {};
      Object.keys(powersDataType).forEach((item) => {
        const array = res.powers.filter((n) => n.type === powersDataType[item]);
        if (array.length > 0) {
          powerObj[item] = array[0].json || [];
        }
      });
      powerObj.newStation = getTreeByCodes(['market', 'group', 'station'], res1.json).treeOptions;
      if (
        Object.keys(powerObj?.settlement || {}).length > 0 &&
        Object.keys(powerObj?.region || {}).length === 0
      ) {
        powerObj.region = [...powerObj.settlement];
      }
      let obj = {};
      if (powerObj.newStation && powerObj.newStation.length > 0) {
        const item = powerObj.newStation[0];
        obj.newSelectStationList = [item.value, item.children?.[0].children?.[0].value];
        obj.newSelectStationId = item.children?.[0].children?.[0].value;
        obj.provinceId = item.provinceId;
      }
      if (powerObj.station && powerObj.station.length > 0) {
        const item = powerObj.station?.[0];
        obj.selectStationList = [item.value, item.children?.[0].value];
        obj.selectStationId = item.children?.[0].value;
      }
      let tDept = powerObj.dept ? powerObj.dept.manageList || [] : [];
      if (tDept.length > 0) {
        const item = tDept[0];
        obj.selectDeptList = [item.deptNum, ''];
        obj.selectDeptId = item.deptId;
      }
      if (powerObj.region && powerObj.region.length > 0) {
        const item = powerObj.region[0];
        obj.selectRegionList = [item.value, item.children[0].value];
      }
      this.setState(
        {
          spinLoding: false,
          errorMsg: '',
          deptList: tDept,
          dataSourceList: powerObj.source,
          decomposeStrategyList: powerObj.strategy,
          stationList: powerObj.station,
          newStationList: powerObj.newStation,
          regionList: powerObj.region,
          ...obj,
        },
        () => {
          onCheckFeed();
          callBack && callBack();
        },
      );
    } else {
      this.setState({ spinLoding: false, errorMsg: (res && res.message) || '' });
    }
  }

  //天机售电测发电测权限接口更改
  async _onGetStationToTianJi(callBack, menuCode) {
    this.setState({ spinLoding: true });
    let res = await queryDataPowerToTianJi(menuCode);
    this._isSpinLoading_ = false;
    if (res && res.statusCode === HttpCode.SUCCESS) {
      let powerObj = {};
      const array = res.powers.find((x) => x.type === powersDataType.region)?.json || [];
      if (array.length > 0) {
        powerObj.region = array.map((x) => ({
          lable: x.lable,
          value: x.value,
          children: (x?.children || []).map((y) => ({
            lable: y.lable,
            value: y.value,
            stationId: y.stationId,
          })),
        }));
      }
      let obj = {};
      if (powerObj.station && powerObj.station.length > 0) {
        const item = powerObj.station[0];
        obj.selectStationList = [item.value, item.children[0].value];
        obj.selectStationId = item.children[0].value;
      }
      let tDept = powerObj.dept ? powerObj.dept.manageList || [] : [];
      if (tDept.length > 0) {
        const item = tDept[0];
        obj.selectDeptList = [item.deptNum, ''];
        obj.selectDeptId = item.deptId;
      }
      if (powerObj.region && powerObj.region.length > 0) {
        const item = powerObj.region[0];
        obj.selectRegionList = [item.value, item.children[0].value];
      }
      this.setState(
        {
          spinLoding: false,
          errorMsg: '',
          deptList: tDept,
          dataSourceList: powerObj.source,
          decomposeStrategyList: powerObj.strategy,
          stationList: powerObj.station,
          regionList: powerObj.region,
          ...obj,
        },
        () => {
          onCheckFeed();
          callBack && callBack();
        },
      );
    } else {
      this.setState({ spinLoding: false, errorMsg: (res && res.message) || '' });
    }
  }

  componentWillUnmount() {
    super.componentWillUnmount();
  }
  async _onCascaderChange(value, type, deptNum = '') {
    let obj = { index: 1 };
    const { dispatch, dashboardIndex } = this.props;
    if (renovate.isRenovate || dashboardIndex === 'confirm') {
      obj = await TRAlert.show('当前工作将不被保存，继续执行此操作？');
    }
    if (obj.index === 1 && dispatch) {
      if (type === 'region') {
        const array = value || [];
        const orginArr = [...this.state.selectRegionList];
        this._onChangeStation({ selectRegionList: array });
        emitter.emit('onChangeRegion', array, orginArr);
      }
      if (type === 'station') {
        const array = value || [];
        const stationId = array.length > 0 ? array[array.length - 1] : '';
        this._onChangeStation({ selectStationList: array, selectStationId: stationId });
        emitter.emit('onChangeUnit', stationId);
      }
      if (type === 'dept') {
        const array = value || '';
        this._onChangeStation({ selectDeptId: array });
        emitter.emit('onChangeRegion', array, deptNum);
      }
    }
  }
  _onGetStationName(array, arr = []) {
    let keyVal = arr[0] || '';
    var end = arr[arr.length - 1];
    array.forEach((item) => {
      if (item.children) {
        item.children.forEach((jitem) => {
          if (end === jitem.stationId) {
            keyVal += '/' + jitem.stationName;
          }
        });
      }
    });
    return keyVal;
  }
  _onTopologyName(array, arr = []) {
    let keyVal = array.length > 0 ? arr[0] : '';
    var end = arr && arr.length > 0 ? arr[arr.length - 1] : {};
    array.forEach((item) => {
      if (item.deptNum === keyVal) {
        keyVal = item.deptName;
      }
      if (item.children) {
        item.children.forEach((jitem) => {
          if (end === jitem.deptNum) {
            keyVal += '/' + jitem.deptName;
          }
        });
      }
    });
    return keyVal;
  }
  _onGetRegionName(array, arr) {
    let keyVal = array.length > 0 ? arr[0] : '';
    var end = arr && arr.length > 0 ? arr[arr.length - 1] : {};
    array.forEach((item) => {
      if (item.value === keyVal) {
        keyVal = item.lable;
      }
      if (item.children) {
        item.children.forEach((jitem) => {
          if (end === jitem.value) {
            keyVal += '/' + jitem.lable;
          }
        });
      }
    });
    return keyVal;
  }
  _onChangeStation(obj) {
    this.setState({
      ...obj,
    });
  }
  _onLoadingRender(isBorder = true, isDack = false) {
    return (
      <div
        className={`${TDark() || isDack ? styles.tDarkbasebox : styles.tbasebox}`}
        style={{ borderTopWidth: `${isBorder ? 1 : 0}px` }}
      >
        <Spin className={styles.spin} />
      </div>
    );
  }
  _onEmptyRender() {
    return <TRDefault type="empty" />;
  }
  _onErrorRender(message) {
    return <TRDefault type="error" message={message} />;
  }

  _onStationRender() {
    const { stationList = [], selectStationList } = this.state;
    const options = filterList(stationList);
    let lastItem = this._onGetStationName(stationList, selectStationList);
    return (
      <div className={styles.header}>
        <Cascader
          value={selectStationList}
          options={options}
          allowClear={false}
          suffixIcon={<CaretDownOutlined className={styles.suffix} />}
          open={true}
          showSearch={{ filter }}
          style={{
            width: lastItem.includes('/')
              ? lastItem.length > 8
                ? lastItem.length * 26
                : lastItem.length * 30
              : lastItem.length > 3
              ? lastItem.length * 30
              : lastItem.length * 40,
          }}
          onChange={(value) => {
            this._onCascaderChange(value, 'station');
          }}
        />
      </div>
    );
  }

  _onStationSelectRender() {
    const { newStationList = [], newSelectStationList } = this.state;
    const newstations = [];
    newStationList.map((x) => {
      // 交易中新
      (x?.children || []).map((y) => {
        newstations.push(y);
      });
    });
    const options = _.uniqBy(newstations, 'marketName').map((i) => ({
      ...i,
      value: i.marketId,
      label: i.marketName,
    }));
    return (
      <Select
        value={newSelectStationList}
        options={options}
        allowClear={false}
        showSearch={true}
        style={{
          width: 200,
          margin: '14px 16px 14px 24px',
        }}
        onChange={(value) => {
          const data = newStationList.find((i) => i.marketId === value);
          const newSelectStationId = data?.children[0]?.children[0]?.value;
          this._onChangeStation({
            newSelectStationList: [value, newSelectStationId],
            newSelectStationId: newSelectStationId,
          });
        }}
      />
    );
  }

  _onStationPowerSelectRender() {
    const { newStationList = [], newSelectStationList, newSelectStationId } = this.state;
    const marketId = newSelectStationList[0];
    let stationOption = newStationList.find((i) => i.value === marketId)?.children || [];
    stationOption = _.flatten(stationOption.map((i) => i?.children || []));
    return (
      <div className={styles.selectRow}>
        <Select
          value={newSelectStationList[0]}
          options={newStationList}
          allowClear={false}
          showSearch={true}
          style={{
            width: 200,
            margin: '14px 16px 14px 24px',
          }}
          onChange={(value) => {
            const data = newStationList.find((i) => i.marketId === value);
            const newSelectStationId = data?.children[0]?.children[0]?.value;
            this._onChangeStation({
              provinceId: data.provinceId,
              newSelectStationList: [value, newSelectStationId],
              newSelectStationId: newSelectStationId,
            });
          }}
        />
        <Select
          showSearch={true}
          style={{
            width: 200,
            margin: '14px 16px 14px 0',
          }}
          options={stationOption}
          value={newSelectStationId}
          placeholder="请选择结算单元"
          filterOption={(inp, option) => option.label.includes(inp)}
          onChange={(value) => {
            this._onChangeStation({ newSelectStationId: value });
          }}
        />
      </div>
    );
  }

  _onRegionRender() {
    const { regionList = [], selectRegionList } = this.state;
    const options = filterList(regionList);
    let lastItem = this._onGetRegionName(regionList, selectRegionList);
    return (
      <div className={styles.header}>
        <Cascader
          value={selectRegionList}
          options={options}
          allowClear={false}
          suffixIcon={<CaretDownOutlined className={styles.suffix} />}
          showSearch={{ filter }}
          style={{
            width: lastItem.includes('/')
              ? lastItem.length > 8
                ? lastItem.length * 26
                : lastItem.length * 30
              : lastItem.length > 3
              ? lastItem.length * 30
              : lastItem.length * 40,
          }}
          onChange={(value) => {
            this._onCascaderChange(value, 'region');
          }}
        />
      </div>
    );
  }

  _onTopologyRender() {
    const { deptList = [] } = this.state;
    let menuDefault = '';
    if (deptList.length > 0 && deptList[0].deptId) {
      menuDefault = deptList[0].deptId;
    }
    return (
      <div className={styles.header}>
        <Select
          defaultValue={menuDefault}
          dropdownMatchSelectWidth={false}
          className={styles.head_select_1}
          onChange={(value, option) => {
            this._onCascaderChange(value, 'dept', option?.deptNum || '');
          }}
          key={menuDefault}
          getPopupContainer={(triggerNode) => triggerNode.parentNode}
        >
          {deptList.map((item) => {
            return (
              <Select.Option value={item.deptId} deptNum={item?.deptNum || ''} key={item.deptId}>
                {item.deptName}
              </Select.Option>
            );
          })}
        </Select>
      </div>
    );
  }

  render() {
    return <div />;
  }
}

export const EmptyRender = () => <TRDefault type="empty" />;
export const ErrorRender = ({ message }) => <TRDefault type="error" message={message} />;
export const LoadingRender = ({ isBorder = true, isDack = false }) => {
  return (
    <div
      className={`${TDark() || isDack ? styles.tDarkbasebox : styles.tbasebox}`}
      style={{ borderTopWidth: `${isBorder ? 1 : 0}px` }}
    >
      <Spin className={styles.spin} />
    </div>
  );
};
